package com.web.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * @author FDjavaone
 * @date 2017/10/27
 */
@Component
@Aspect
@Slf4j
public class IPAspect {

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @Pointcut("@annotation(com.web.annotation.IPAccess)")
    private void point() {

    }

    @Around("point()")
    public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[1];
        HttpServletResponse response = (HttpServletResponse) args[2];
        String UNKNOWN = "unknown";
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        log.info("访问者ip：" + ip);
        String count = stringRedisTemplate.opsForValue().get(ip);
        if (count == null) {
            count = "0";
        }
        stringRedisTemplate.opsForValue().set(ip, String.valueOf(Integer.parseInt(count) + 1), 1, TimeUnit.DAYS);
        if (Integer.parseInt(count) > 4) {
            log.info("验证不通过！");
            response.setContentType("application/json;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            out.write("{\"status\":999999,\"message\":\"由于您的预注册过于频繁，系统禁止访问！若您当前是连接WIFI，请关闭WIFi后重新尝试注册！\"}".getBytes("utf-8"));
            return null;
        }
        return joinPoint.proceed();

    }

}
